package com.thymeleaf.demo.config;


import com.thymeleaf.demo.myexception.MyExcption;
import com.thymeleaf.demo.util.result.BaseResult;
import com.thymeleaf.demo.util.result.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalException extends RuntimeException{

    @Autowired
    ResultUtil resultUtil;

    /*
    自定义异常处理
     */
    @ExceptionHandler(value = {Exception.class, NullPointerException.class})
    @ResponseBody
    public BaseResult<String> defaultErrorHandler(HttpServletRequest request, Exception e){
        String errorMessage = e.getMessage();
        if(e instanceof MyExcption){
            return resultUtil.error(Integer.valueOf(errorMessage));
        }else{
            // 系统异常
            return resultUtil.error(500, errorMessage);
        }
    }
}
